package com.tang.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.tang.reggie.common.BaseContext;
import com.tang.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String[] uris=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        String requestURI = request.getRequestURI();
        //log.info("拦截到的请求：{}",requestURI);
        boolean check = check(uris, requestURI);
        if (check){
            log.info("放行，不处理请求：{}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        Long id =(Long) request.getSession().getAttribute("employee");
        if (id!=null){
            log.info("放行，登录后的请求：{}",requestURI);
            BaseContext.setCurrentId(id);//当前线程获取到登录的id
            filterChain.doFilter(request,response);
            BaseContext.remove();
            return;
        }

        // TODO 后台前台登录Bug
        /*
        这里有bug，如果是前台登录，那你就必须先把后台注销掉，或者这里的前台过滤无效了
        如果是后台登录，那么就把前台注销掉
         */
        Long userId =(Long) request.getSession().getAttribute("user");
        if (userId!=null){
            log.info("放行，登录后的请求：{}",requestURI);
            BaseContext.setCurrentId(userId);//当前线程获取到登录的id
            filterChain.doFilter(request,response);
            BaseContext.remove();
            return;
        }

        log.info("不放行的请求：{}",requestURI);
        //未登录，返回给前端，让它进行跳转
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String[] uris,String requestURI){
        for (String s : uris) {
            if (PATH_MATCHER.match(s,requestURI)){
                return true;
            }
        }
        return false;
    }
}
